﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Rung.Net.Cache
{
    /// <summary>
    /// 传输中的文件信息基类。
    /// </summary>
    internal abstract class FileItemBM
    {
        internal ushort Id { get; set; }

        /// <summary>
        /// 在 Send(byte[] data) 方法发起的传输中，表示完整数据。
        /// 消息发起方会将该数据分包发送，消息接收方会将接收到的分包数据组合到该数据中。
        /// </summary>
        internal byte[] Buffer { get; set; }

        /// <summary>
        /// 保存接收文件的临时文件。
        /// 该文件的实体在接收方收到“一次握手”通知时创建。
        /// </summary>
        internal FileInfo FileInfo { get; set; }

        /// <summary>
        /// 当前 已发送/已接受 的包的总数。
        /// </summary>
        internal int PackageCountReceived
        { get; set; }

        /// <summary>
        /// 待发送文件的总长度。
        /// </summary>
        internal long FileLength
        {
            get { return this.FileInfo.Length; }
        }

        internal FileItemBM() { }

        internal FileItemBM(ushort id, FileInfo fi, int bufferLength)
        {
            this.Id = id;
            this.FileInfo = fi;
            this.Buffer = new byte[bufferLength];
            this.PackageCountReceived = 0;
        }
    }

    internal class FileItemClientBM : FileItemBM, IDisposable
    {
        internal FileStream Stream { get; set; }

        internal FileItemClientBM() { }

        internal FileItemClientBM(ushort id, FileInfo fi, int bufferLength)
            : base(id, fi, bufferLength)
        {
            this.Stream = base.FileInfo.OpenWrite();
        }

        public void Dispose()
        {
            if (Stream != null)
            {
                Stream.Close();
            }
        }
    }

    internal class FileItemServerBM : FileItemBM, IDisposable
    {
        internal string SourceFileName { get; set; }

        internal FileStream Stream { get; set; }

        internal byte[] PackageBuffer { get; set; }

        internal int PackageBufferLength { get; set; }

        internal int PackageBufferValidLength { get; set; }

        internal FileItemServerBM() { }

        internal FileItemServerBM(ushort id, FileInfo fi, int bufferLength)
            : base(id, fi, bufferLength)
        {
            this.Stream = base.FileInfo.OpenRead();
            this.PackageBufferLength = 2 * bufferLength;
            this.PackageBuffer = new byte[this.PackageBufferLength];
            this.PackageBufferValidLength = 0;
        }

        public void Dispose()
        {
            if (Stream != null)
            {
                Stream.Close();
            }
        }
    }
}
